using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Random = UnityEngine.Random;

namespace GameCore
{
    [Serializable]
    public struct AreaConnections
    {
        public AreaConfig target;
        public bool fixedConnection;
        public float chance;
    }

    [Serializable]
    public struct WeightedLootEntry
    {
        public float weight;
        public WorldItem item;
    }
    
    [CreateAssetMenu(fileName = "New Area", menuName = "Game/Area Config")]
    public class AreaConfig : ScriptableObject
    {
        public ResourceID areaID;
        public int steps;
        public bool canEvacuate;
        public int itemCount;
        public Sprite inactiveSprite;
        public Sprite activeSprite;
        public Sprite selectedSprite;
        public List<AreaConnections> connections;
        public Texture2D background;

        
        
        public List<WeightedLootEntry> itemLoots;
        public List<WeightedLootEntry> backpackLoots;

        public WorldItem GetRandomItem()
        {
            float totalWeight = itemLoots.Sum(item => item.weight);
            float r = Random.value * totalWeight;
            float w = 0;
            foreach (var entry in itemLoots)
            {
                w += entry.weight;
                if (r < w) return entry.item;
            }
            return null;
        }

        public WorldItem GetRandomBackpack()
        {
            float totalWeight = backpackLoots.Sum(item => item.weight);
            float r = Random.value * totalWeight;
            float w = 0;
            foreach (var entry in backpackLoots)
            {
                w += entry.weight;
                if (r < w) return entry.item;
            }
            return null;
        }

        public List<AreaConfig> GetRandomConnections()
        {
            var ret = new List<AreaConfig>();
            foreach (var connection in connections)
            {
                if (connection.fixedConnection || Random.value < connection.chance)
                    ret.Add(connection.target);
            }
            return ret;
        }
    }
}